package com.paradogs.framework.core.netty;

import com.paradogs.framework.common.pojo.gc.GCAllocGateway;
import com.paradogs.framework.core.msg.PRMsg;
import com.paradogs.framework.core.msg.ByteData;
import com.paradogs.framework.core.msg.MsgHeader;
import com.paradogs.framework.core.utils.ProtoUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: yumi
 * @date: 2023-02-08  11:43
 * @Description: TODO
 * Not allowed to be shared !!
 * ps: 继承 BaseMsg 的实体类不能加 @slf4j，会被 JProtobuf 解析导致编码失败
 */
@Slf4j
@Component
@Scope("prototype")
public class PRCodec extends ByteToMessageCodec<PRMsg> {

    @Override
    protected void encode(ChannelHandlerContext ctx, PRMsg msg, ByteBuf out) throws Exception {

        try {
            msg.getMsgHeader().serialization(out);
            msg.serialization(out);
        } catch (Exception e) {
            log.error("Encode error: {}", e.getMessage(), e);
        }

    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

        // 读取请求头
        MsgHeader header = new MsgHeader();
        header.deserialization(in);

        // 消息体暂时不解析，放 MsgHandler 中解析
        ByteData byteDataMsg = new ByteData();
        byteDataMsg.setMsgHeader(header);
        byteDataMsg.deserialization(in);

        out.add(byteDataMsg);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("{}", cause.getMessage(), cause);
        super.exceptionCaught(ctx, cause);
    }
}
